package com.space.school.services.impl;

import com.space.school.dao.UserDao;
import com.space.school.dao.impl.UserDaoImpl;
import com.space.school.domain.User;
import com.space.school.services.UserService;
import com.space.school.utils.PageBean;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoImpl();
    @Override
    public PageBean<User> search(int currentPage, int pageSize,Map<String,String[]> map) {
//        从第几个数据开始
        int start=(currentPage-1)*pageSize;
        List<User> list=userDao.search(start,pageSize,map);
        PageBean<User> pb=new PageBean<User>();
        pb.setList(list);
//        总数据数
        int count=userDao.count(map);
        pb.setTotalCount(count);
//        每页显示数据数
        pb.setRows(pageSize);
//        当前页
        pb.setCurrentPage(currentPage);
//        总页数
//        int Totalpage=(int)Math.ceil((double)count/pageSize);
        int totalPage =(count%pageSize==0 ? count/pageSize : count/pageSize+1);
        pb.setTotalPage(totalPage);
        return pb;

    }

    @Override
    public int delete(int id) {
        return userDao.delete(id);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public User findById(int id) {
        return userDao.findById(id);
    }

    @Override
    public void updateStatus(int id, String status) {
        if(status.equals("1")){
            status="0";
        }else {
            status="1";
        }
        userDao.updateStatus(id, status);
    }

    @Override
    public String save(User user) {
        //    1.账户已存在,不能注册,
        String message="";
        boolean flag= userDao.existUsername(user.getUserName());
        if(flag){
            //    2.密ma是否太简单了
            boolean difficultyFlag=difficultyPassword(user.getPassWord());
            if(difficultyFlag){
                userDao.save(user);
                return message;
            }else {
                message="密码过于简单";
                return message;
            }

        }else {
            message="账户已存在,不能注册";
            return message;
        }

    }
    public static boolean difficultyPassword(String password) {
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{6}$";
        return Pattern.matches(regex, password);
    }
}
